import { Injectable } from '@nestjs/common';
import { eq, and, like, or, sql } from 'drizzle-orm';
import { DrizzleService } from '../../db/drizzle.service';
import { depts } from '../../db/schema';
import { CreateDeptDto, UpdateDeptDto, QueryDeptDto } from './dto/dept.schema';

@Injectable()
export class DeptService {
  constructor(private readonly drizzle: DrizzleService) { }

  async create(dept: CreateDeptDto) {
    return await this.drizzle.db.insert(depts).values(dept);
  }

  async findAll(query?: QueryDeptDto) {
    const { deptName, status, parentId, pageNum = '1', pageSize = '10' } = query;
    
    // 构建查询条件
    const conditions = [];
    
    if (deptName) {
      conditions.push(like(depts.deptName, `%${deptName}%`));
    }
    
    if (status) {
      conditions.push(eq(depts.status, status));
    }
    
    if (parentId) {
      conditions.push(eq(depts.parentId, Number(parentId)));
    }
    
    // 计算分页参数
    const limit = Number(pageSize);
    const offset = (Number(pageNum) - 1) * limit;
    
    // 查询总数
    const countResult = await this.drizzle.db
      .select({ count: sql<number>`count(*)` })
      .from(depts)
      .where(conditions.length > 0 ? and(...conditions) : undefined);
    
    const total = Number(countResult[0].count);
    
    // 查询分页数据
    const data = await this.drizzle.db
      .select()
      .from(depts)
      .where(conditions.length > 0 ? and(...conditions) : undefined)
      .orderBy(depts.orderNum, depts.deptId)
      .limit(limit)
      .offset(offset);
    
    return {
      data,
      total,
      pageNum: Number(pageNum),
      pageSize: limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  async findOne(id: number) {
    return await this.drizzle.db
      .select()
      .from(depts)
      .where(eq(depts.deptId, id));
  }

  async update(id: number, dept: UpdateDeptDto) {
    return await this.drizzle.db
      .update(depts)
      .set(dept)
      .where(eq(depts.deptId, id));
  }

  async remove(id: number) {
    return await this.drizzle.db
      .delete(depts)
      .where(eq(depts.deptId, id));
  }
}